<template>
  <view class="container">
    <view class="top-txt">
      {{ cates[questionList[shuffleIndex[index]].cate_id].content }}
    </view>

    <!-- view class='bg-pic' style="background:url({{imagePath}}/app4/bg2.jpg)" -->
    <view class="bg-pic">
      <image :src="imagePath + '/app4/bg2.jpg'" />
      <image v-if="showcatebg" class="cover" :src="imagePath + '/app4/catebg/' + cates[questionList[shuffleIndex[index]].cate_id].title + '.png'" />
    </view>

    <view class="faq">
      <view class="faq-num">
        {{ index + 1 }}/{{ num }}
      </view>

      <view class="line">
        <image :src="imagePath + '/app4/line.png'" />
      </view>

      <view class="tit">
        {{ questionList[shuffleIndex[index]].question }}
        {{ questionList[shuffleIndex[index]].type == 1 || questionList[shuffleIndex[index]].type == 3 ? '【单选】' : '【多选】' }}
      </view>
      <!-- （{{questionList[shuffleIndex[index]].scores}}分） -->
      <view class="line">
        <image :src="imagePath + '/app4/line.png'" />
      </view>

      <view class="faq-box">
        <radio-group v-if="questionList[shuffleIndex[index]].type == 1" class="radio-group" @change="radioChange">
          <label
            v-for="(value, key) in questionList[shuffleIndex[index]].option"
            :key="key"
            :style="questionList[shuffleIndex[index]].options_type == 2 ? 'display:inline-block' : ''"
            :data-index="key"
            :class="'item radio my-choosebox ' + (key === activeItemIndex ? 'active' : '') + ' ' + (questionList[shuffleIndex[index]].options_type == 2 ? 'hafe' : '')"
            @tap="changestyle"
          >
            <block v-if="questionList[shuffleIndex[index]].options_type == 2">
              <view class="view" style="wdith:line-height:100rpx;" @tap="changestyle">
                <radio :data-index="key" :value="key" :checked="questionList[shuffleIndex[index]].checked" @tap="changestyle" />
                {{ key }}、
                <image :data-index="key" style="object-fit: cover; width: 100%; height: 180rpx" :src="value.value" @tap="changestyle" />
              </view>
            </block>

            <block v-else>
              <radio :data-index="key" :value="key" :checked="questionList[shuffleIndex[index]].checked" @tap="changestyle" />
              {{ key }}、{{ value.value }}
            </block>
          </label>
        </radio-group>

        <checkbox-group v-else-if="questionList[shuffleIndex[index]].type == 2" @change="checkboxChange">
          <label
            v-for="(value, key) in questionList[shuffleIndex[index]].option"
            :key="key"
            :style="questionList[shuffleIndex[index]].options_type == 2 ? 'display:inline-block' : ''"
            :data-index="key"
            :class="'item checkbox my-choosebox    ' + (questionList[shuffleIndex[index]].options_type == 2 ? 'hafe' : '') + ' ' + (value.ischeck ? 'ischeck' : '')"
            @tap="changestyle"
          >
            <block v-if="questionList[shuffleIndex[index]].options_type == 2" :data-index="key" @tap.native="changestyle($event, { index: key })">
              <view class="view" style="wdith:line-height:100rpx;" @tap="changestyle">
                <checkbox :value="key" :checked="questionList[shuffleIndex[index]].checked" />
                {{ key }}、
                <image :data-index="key" style="object-fit: cover; width: 100%; height: 180rpx" :src="value.value" @tap="changestyle" />
              </view>
            </block>

            <block v-else>
              <checkbox :data-index="key" :value="key" :checked="questionList[shuffleIndex[index]].checked" @tap="changestyle" />
              {{ key }}、{{ value.value }}
            </block>
          </label>
        </checkbox-group>

        <radio-group v-else class="radio-group" @change="radioChange">
          <label
            v-for="(item, index) in questionList[shuffleIndex[index]].option"
            :key="index"
            :data-index="key"
            :class="'item radio my-choosebox ' + (key === activeItemIndex ? 'active' : '')"
            @tap="changestyle"
          >
            <radio :value="item" :checked="questionList[shuffleIndex[index]].checked" />

            {{ item }}
          </label>
        </radio-group>
      </view>
    </view>

    <view class="faq-btn">
      <block v-if="isanswer">
        <view class="btn-box">
          <block v-if="answer_true">
            <!-- <button class='btn'><image src="{{imagePath}}/app4/right.png"></image>回答正确</button> -->
            <button class="btn" @tap="nextSubmit">
              <image :src="imagePath + '/app4/right.png'" />
              {{ nexbutton_txt }}
            </button>
          </block>

          <block v-else>
            <button class="btn" @tap="requeren">
              <image :src="imagePath + '/app4/wrong.png'" />
              重新回答
            </button>
            <!-- <button class='btn' bindtap='nextSubmit'>下一题</button> -->
          </block>
        </view>
      </block>

      <block v-else>
        <button class="btn" hover-class="btn-hover" @tap="queren">
          确定
        </button>
      </block>

      <!--view wx:if="{{answer_true}}" class="text"><image style="width:20px;height:20px;" src="{{imagePath}}/app4/right.png"></image><text>回答正确</text></view>
			<view wx:else class="text"><image  style="width:20px;height:20px;" src="{{imagePath}}/app4/wrong.png"></image><text>回答错误</text></view-->

      <!-- button class='btn' bindtap='requeren' style="display:{{reanwser_box_display}}">重新回答</button -->
      <!-- button class='btn' hover-class="btn-hover" bindtap='nextSubmit' style="display:{{next_box_display}}">下一题</button -->

      <!-- <button bindtap='outTest' class="toindex-btn">退出答题</button> -->
    </view>

    <!-- 这里是弹出框，回答问题点确定之后弹出。 -->

    <view class="pop-box" :style="'display:' + pop_box_display">
      <text>正确答案为：{{ trueValue }}</text>
      <view class="faq-tips">
        {{ cates[questionList[shuffleIndex[index]].cate_id].content }}
      </view>

      <view style="color: #ffffff; font-size: 32rpx; position: absolute; right: 10rpx; bottom: 10rpx">
        {{ second }}
      </view>
    </view>
  </view>
</template>

<script>
// 006-1.js
let app = getApp();
import service from '../../service/service';
import { questionList, questionDetail } from '../../service/api';
let setTimer;
// var jsonList = require('../../data/json.js');
export default {
    data() {
        return {
            imagePath: app.globalData.imagePath,
            anwser_box_display: 'block',
            reanwser_box_display: 'none',
            next_box_display: 'none',
            questionList: [],
            nexbutton_txt: '下一题',
            height: 20,
            focus: false,
            text: '点击文字输入框输入文字',
            list: [],
            cates: [],
            size: 20,
            page: 1,
            index: 0,

            // 题目序列
            num: 10,

            second: 10,
            chooseValue: [],

            // 选择的答案序列
            totalScore: 100,

            // 总分
            right: 0,

            // 答对的题目数量
            wrong: 0,

            // 错误的题目数量
            wrongList: [],

            // 错误的题目集合-乱序
            wrongListSort: [],

            // 错误的题目集合-正序
            pop_box_display: 'none',

            isjump: false,
            shuffleIndex: '',
            showcatebg: false,
            str: '',
            isanswer: false,
            activeItemIndex: '',
            answer_true: false,
            trueValue: '',
            alreadySend: false,
            send: false,
            content: '',
            cate_id: '',
            title: '',
            question: '',
            type: 0,
            options_type: 0,
            option: [],
            checked: '',

            value: {
                value: '',
                ischeck: false
            }
        };
    },
    onLoad: function (options) {
        let that = this;
        that.listFun();
        // //console.log(options);

        // options.testId = "101-1"

        // var  questionList  = jsonList.questionList[options.testId];
        // wx.setNavigationBarTitle({ title: options.testId }) // 动态设置导航条标题

        // this.setData({
        //   questionList: questionList,  // 拿到答题数据
        //   // testId: options.testId // 课程ID
        // })
        // that.setShuffleindex();
    },
    methods: {
        listFun: function () {
            let that = this;
            const page = this.page;
            const size = this.size;
            console.log('------------------')
            //console.log(this.data.page)
            uni.showLoading({
                title: '加载中',
                mask: true
            });
            service({
                ...questionList,
                data: {
                    page: page,
                    size: size
                }
            })
                .then((resp) => {
                    console.log('11222');
                    uni.hideLoading();
                    let concat = this.list.concat(resp.data.list);
                    //console.log(concat);
                    concat.forEach((item, index) => {
                        //console.log(item);
                        // if (item.title && item.title.length > 16) {
                        //   item.title = item.title.substring(0, 16) + "...";
                        // }

                        let option_new = new Object();
                        let toption = item.option;
                        for (let key in toption) {
                            //console.log(key + '---' + toption[key])
                            let mycars = new Object();
                            mycars['ischeck'] = false;
                            mycars['value'] = toption[key];
                            let tkey = key;
                            option_new[tkey] = mycars;
                        }
                        item.option = option_new;
                    });

                    //console.log(concat);
                    // //console.log(resp.data.cates);

                    try {
                        // 同步接口立即写入
                        uni.setStorageSync('questionList', concat);
                        uni.setStorageSync('cates', cates);
                        //console.log('写入value2成功')
                    } catch (e) {
                        console.log('CatchClause', e);
                        console.log('CatchClause', e);
                    } //console.log('写入value2发生错误')
                    this.setData({
                        questionList: concat,
                        cates: resp.data.cates,
                        page: page + 1
                    });
                    // this.setData({
                    //   questionList: questionList,  // 拿到答题数据
                    //   // testId: options.testId // 课程ID
                    // })
                    that.setShuffleindex();
                    if (resp.data.length != 0) {
                        // wx.showToast({
                        //   title: "加载第" + (page + 1) + "页成功",
                        //   icon: "success"
                        // });
                    } else {
                        uni.showToast({
                            title: '我是有底线的',
                            icon: 'none'
                        });
                    }
                })
                .catch((error) => {
                    //console.log("请求列表失败", error);
                });
        },

        setShuffleindex: function () {
            // //console.log(this.data.questionList);

            // var testId =  "101-1";
            let count = this.generateArray(0, this.questionList.length - 1); // 生成题序
            // let num = testId == '102' || testId == '301-302'?20:10;  // 102/301-302 试题有20道题

            // this.setData({
            //   shuffleIndex: this.shuffle(count).slice(0, num) // 生成随机题序 [2,0,3] 并截取num道题
            // })

            this.setData({
                // shuffleIndex: this.shuffle(count).slice(0,  this.data.questionList.length-1) // 生成随机题序 [2,0,3] 并截取num道题
                shuffleIndex: this.shuffle(count).slice(0, this.num),
                // 生成随机题序 [2,0,3] 并截取num道题
                showcatebg: true
            });

            //console.log(this.data.cates)
        },

        /*
         * 数组乱序/洗牌
         */
        shuffle: function (arr) {
            let i = arr.length;
            while (i) {
                let j = Math.floor(Math.random() * i--);
                [arr[j], arr[i]] = [arr[i], arr[j]];
            }
            return arr;
        },

        /*
         * 单选事件
         */
        radioChange: function (e) {
            // //console.log('checkbox发生change事件，携带value值为：', e.detail.value)
            this.chooseValue[this.index] = e.detail.value;
            //console.log(this.data.chooseValue);
        },

        /*
         * 多选事件
         */
        checkboxChange: function (e) {
            // //console.log('checkbox发生change事件，携带value值为：', e.detail.value)
            // //console.log('checkbox发生change事件，携带value值为：',  this.data.questionList[this.data.shuffleIndex[this.data.index]].option)

            this.chooseValue[this.index] = e.detail.value.sort();
            // //console.log(this.data.chooseValue);
            // //console.log('111111111111');

            let nowoption = this.questionList[this.shuffleIndex[this.index]].option;
            for (let key1 in nowoption) {
                // //console.log(nowoption[key1])
                if (this.my_in_array(key1, e.detail.value)) {
                    nowoption[key1].ischeck = true;
                } else {
                    nowoption[key1].ischeck = false;
                }
            }
            this.questionList[this.shuffleIndex[this.index]].option;
            let str = 'questionList[' + this.shuffleIndex[this.index] + '].option';
            // //console.log(str)
            this.setData({
                [str]: nowoption
            });
        },

        my_in_array: function (search, array) {
            for (let i in array) {
                if (array[i] == search) {
                    return true;
                }
            }
            return false;
        },

        /*
         * 退出答题 按钮
         */
        outTest: function () {
            uni.showModal({
                title: '提示',
                content: '你真的要退出答题吗？',
                success(res) {
                    if (res.confirm) {
                        //console.log('用户点击确定')
                        uni.switchTab({
                            url: '../home/home'
                        });
                    } else if (res.cancel) {
                        //console.log('用户点击取消')
                    }
                }
            });
        },

        /*
         * 重新答题
         */
        requeren: function () {
            this.setData({
                isanswer: false,
                pop_box_display: 'none'
            });
            // var nowoption = this.data.questionList[this.data.shuffleIndex[this.data.index]].option;
            // for(let key1  in nowoption){
            //       // //console.log(nowoption[key1])
            //       nowoption[key1].ischeck = false;
            // }
            // this.data.questionList[this.data.shuffleIndex[this.data.index]].option;
            // var str = 'questionList['+this.data.shuffleIndex[this.data.index]+'].option';
            // this.setData({
            //   [str]: nowoption,
            //   activeItemIndex: -1
            // })
        },

        /*
         * 下一题/提交 按钮
         */
        queren: function () {
            // 如果没有选择
            if (this.chooseValue[this.index] == undefined || this.chooseValue[this.index].length == 0) {
                uni.showToast({
                    title: '请选择至少一个答案!',
                    icon: 'none',
                    duration: 2000,
                    success: function () {
                        return;
                    }
                });
                return;
            }

            // 判断答案是否正确
            this.chooseError();

            // // 判断是不是最后一题
            // if (this.data.index < this.data.shuffleIndex.length - 1) {
            //   // 渲染下一题
            //   this.setData({
            //     index: this.data.index + 1
            //   })
            // } else {
            //   let wrongList = JSON.stringify(this.data.wrongList);
            //   let wrongListSort = JSON.stringify(this.data.wrongListSort);
            //   let chooseValue = JSON.stringify(this.data.chooseValue);
            //   wx.navigateTo({
            //     url: '/pages/app4/results?totalScore=' + this.data.totalScore + '&wrongList=' + wrongList + '&chooseValue=' + chooseValue + '&wrongListSort=' + wrongListSort + '&testId=' + this.data.testId
            //   })

            //   // 设置缓存
            //   var logs = wx.getStorageSync('logs') || []
            //   let logsList = { "date": Date.now(), "testId": this.data.testId, "score": this.data.totalScore }
            //   logs.unshift(logsList);
            //   wx.setStorageSync('logs', logs);
            // }
        },

        nextSubmit: function () {
            clearInterval(setTimer);
            // // 如果没有选择
            // if (this.data.chooseValue[this.data.index] == undefined || this.data.chooseValue[this.data.index].length == 0) {
            //   wx.showToast({
            //     title: '请选择至少一个答案!',
            //     icon: 'none',
            //     duration: 2000,
            //     success: function(){
            //       return;
            //     }
            //   })
            //   return;
            // }

            // // 判断答案是否正确
            // this.chooseError();
            // 渲染下一题
            this.setData({
                pop_box_display: 'none',
                activeItemIndex: ''
            });

            // 判断是不是最后一题
            //console.log(this.data.shuffleIndex.length )

            if (this.index < this.shuffleIndex.length - 1) {
                // 渲染下一题
                this.setData({
                    isanswer: false,
                    index: this.index + 1
                });
            } else {
                if (!this.isjump) {
                    this.setData({
                        isjump: true
                    });
                    let wrongList = JSON.stringify(this.wrongList);
                    let wrongListSort = JSON.stringify(this.wrongListSort);
                    let chooseValue = JSON.stringify(this.chooseValue);
                    uni.navigateTo({
                        // url: '/pages/app4/results?totalScore=' + this.data.totalScore + '&wrongList=' + wrongList + '&chooseValue=' + chooseValue + '&wrongListSort=' + wrongListSort + '&testId=' + this.data.testId
                        url: '/pages/app4/results?right=' + this.right
                    });

                    // 设置缓存
                    let logs = uni.getStorageSync('logs') || [];
                    let logsList = {
                        date: Date.now(),
                        testId: this.testId,
                        score: this.totalScore
                    };
                    logs.unshift(logsList);
                    uni.setStorageSync('logs', logs);
                }
            }
        },

        /*
         * 错题处理
         */
        chooseError: function () {
            let trueValue = this.questionList[this.shuffleIndex[this.index]]['true'];
            let chooseVal = this.chooseValue[this.index];
            console.log('选择了' + chooseVal + '答案是' + trueValue);
            let astr = chooseVal.toString();
            astr = astr.replace(/,/g, '');
            console.log('选择了' + astr + '答案是' + trueValue);
            if (astr != trueValue.toString()) {
                //console.log('错了');
                this.wrong++;
                this.wrongListSort.push(this.index);
                this.wrongList.push(this.shuffleIndex[this.index]);
                this.setData({
                    totalScore: this.totalScore - this.questionList[this.shuffleIndex[this.index]]['scores'],
                    // 扣分操作
                    answer_true: false,
                    isanswer: true,
                    pop_box_display: 'flex',
                    trueValue: trueValue,
                    second: 10
                });
                this.autore();
            } else {
                this.right++;
                this.setData({
                    isanswer: true,
                    answer_true: true,
                    pop_box_display: 'flex',
                    trueValue: trueValue,
                    second: 10
                });

                //如果是最后一题 如果是最后一题 答对了 显示查看结果
                if (this.index >= this.shuffleIndex.length - 1) {
                    this.setData({
                        nexbutton_txt: '查看结果'
                    });
                }
                this.autonext();
            }
        },

        autore: function () {
            let that = this;
            clearInterval(setTimer);
            setTimer = setInterval(function () {
                that.setData({
                    second: that.second - 1
                });
                if (that.second <= 0) {
                    that.setData({
                        second: 10,
                        alreadySend: false,
                        send: true,
                        pop_box_display: 'none',
                        isanswer: false
                    });

                    // var nowoption = that.data.questionList[that.data.shuffleIndex[that.data.index]].option;
                    // for(let key1  in nowoption){
                    //       // //console.log(nowoption[key1])
                    //       nowoption[key1].ischeck = false;
                    // }
                    // that.data.questionList[that.data.shuffleIndex[that.data.index]].option;
                    // var str = 'questionList['+that.data.shuffleIndex[that.data.index]+'].option';
                    // that.setData({
                    //   [str]: nowoption,
                    //   activeItemIndex: e.target.dataset.index
                    // });
                    clearInterval(setTimer);
                    // that.nextSubmit()
                }
            }, 1000);
        },

        autonext: function () {
            let that = this;
            clearInterval(setTimer);
            setTimer = setInterval(function () {
                that.setData({
                    second: that.second - 1
                });
                if (that.second <= 0) {
                    that.setData({
                        second: 10,
                        alreadySend: false,
                        send: true
                    });
                    clearInterval(setTimer);
                    that.nextSubmit();
                }

                // that.nextSubmit()
            }, 1000);
        },

        // autonext:function(){
        //   var that =this;
        //     let promise = new Promise((resolve, reject) => {
        //        setTimer = setInterval(
        //         () => {
        //           this.setData({
        //             second: this.data.second - 1
        //           })
        //           if (this.data.second <= 0) {

        //             this.setData({
        //               second: 10,
        //               alreadySend: false,
        //               send: true
        //             })
        //             resolve(setTimer)
        //             that.nextSubmit()
        //           }
        //         }
        //         , 1000)
        //     })
        //     promise.then((setTimer) => {
        //       clearInterval(setTimer)
        //     })
        // },
        /**
         * 生成一个从 start 到 end 的连续数组
         * @param start
         * @param end
         */
        generateArray: function (start, end) {
            return Array.from(new Array(end + 1).keys()).slice(start);
        },

        changestyle: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            //console.log(  e)
            this.setData({
                activeItemIndex: e.target.dataset.index
            });
        }
    }
};
</script>
<style>
page {
    height: 100%;
}
.container {
    width: 100%;
    height: 100%;
    padding: 70rpx 30rpx 50px;
    box-sizing: border-box;
    position: relative;
}

.top-txt {
    display: none;
}

.bg-pic {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}
.bg-pic > image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    position: relative;
    z-index: 5;
}
.bg-pic > image.cover {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 8;
}

.header {
    position: relative;
    z-index: 10;
    width: 100%;
}
.header image {
    width: 485rpx;
    height: 68rpx;
}

.faq {
    position: relative;
    z-index: 10;
    margin-top: 50rpx;
}

.faq-num {
    margin-bottom: 10rpx;
    color: #d01b14;
    font-size: 50rpx;
    font-weight: bold;
}

.line {
    width: 100%;
}
.line > image {
    width: 100%;
    height: 1px;
    display: block;
}

.faq .tit {
    background: #d40009;
    padding: 20rpx 20rpx;
    font-size: 36rpx;
    color: #fff;
    letter-spacing: 2px;
    line-height: 1.5;
    text-shadow: 0 9px 9px rgba(0, 0, 0, 0.36);
    box-shadow: 0 0 10px 3px rgba(63, 62, 62, 0.2);
    margin: 15rpx 0;
    max-height: 25vh;
    overflow-y: auto;
}

.faq-box {
    padding: 10rpx;
}
.faq-box .item {
    padding: 5rpx 20rpx;
    font-size: 34rpx;
    color: #d21b12;
    margin-top: 10px;
    cursor: pointer;
    position: relative;
}
.faq-box .item radio,
.faq-box .item checkbox {
    display: none;
}
.faq-box .active,
.faq-box .ischeck {
    color: #000;
}
.faq-box .hafe {
    margin: 10rpx;
    width: 40%;
}
.faq-box .hafe .view {
    padding: 10rpx;
}
.faq-box .active .view {
    border: 1px solid #d40009;
}
.faq-box .ischeck .view {
    border: 1px solid #d40009;
}

.faq-box .item .state {
    position: absolute;
    right: 10rpx;
    top: calc(50% - 18rpx);
}
.faq-box .item .state image {
    width: 36rpx;
    height: 36rpx;
}

.faq-btn {
    position: absolute;
    bottom: 160rpx;
    left: 0;
    right: 0;
    z-index: 10;
    width: 100%;
    text-align: center;
    box-sizing: border-box;
}

.faq-btn .btn {
    width: 240rpx;
    background: #bd150d;
    border-radius: 45rpx;
    padding: 15rpx 0;
    font-size: 34rpx;
    color: #fff;
    letter-spacing: 2px;
    text-shadow: 0 9px 9px rgba(0, 0, 0, 0.36);
    box-shadow: 5px 2px 15px rgba(0, 0, 0, 0.2) inset;
    overflow: inherit;
    margin: 0;
    display: inline-block;
}
.faq-btn button[disabled='true'] {
    background: #bd150d !important;
}
.btn-box {
    display: flex;
    -webkit-justify-content: center;
    align-items: center;
    padding: 0 50rpx;
}

.btn-box .btn {
    position: relative;
}
.btn-box .btn image {
    width: 40rpx;
    height: 40rpx;
    position: absolute;
    left: -50rpx;
    top: 20rpx;
}
.btn-box .btn:last-child {
    margin-left: 20rpx;
}

.pop-box {
    position: absolute;
    z-index: 20;
    top: 145rpx;
    bottom: 255rpx;
    left: 30rpx;
    right: 30rpx;
    padding: 30rpx;
    box-sizing: border-box;
    background: rgba(0, 0, 0, 0.66);
    display: flex;
    flex-wrap: wrap;
    align-content: center;
}
.pop-box text {
    font-size: 50rpx;
    font-weight: bold;
    color: #fff;
    border-bottom: 1px solid #f1db91;
    padding: 0 0 20rpx 0;
    width: 100%;
}

.faq-tips {
    margin-top: 20rpx;
    font-size: 30rpx;
    color: #fff;
    line-height: 24px;
}

/* pages/test/test.wxss */
.page {
    padding: 20rpx;
}
.page__bd {
    padding: 20rpx;
}
.my-choosebox {
    display: block;
    margin-bottom: 20rpx;
}
.toindex-btn {
    margin-top: 20rpx;
    display: inline-block;
    line-height: 2.3;
    font-size: 13px;
    padding: 0 1.34em;
    color: #576b95;
    text-decoration: underline;
    float: right;
}
</style>
